<?php
// +----------------------------------------------------------------------+
// | Author:  Evgeny Leontev <eleontev@gmail.com>                         |
// | Copyright (c) 2005 Evgeny Leontev                                    |
// +----------------------------------------------------------------------+
// | This source file is free software; you can redistribute it and/or    |
// | modify it under the terms of the GNU Lesser General Public           |
// | License as published by the Free Software Foundation; either         |
// | version 2.1 of the License, or (at your option) any later version.   |
// |                                                                      |
// | This source file is distributed in the hope that it will be useful,  |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of       |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU    |
// | Lesser General Public License for more details.                      |
// +----------------------------------------------------------------------+

class AppView extends BaseView
{
	
	var $popup = false;
	var $popup_var = 'popup';
	var $form_val = array();
	var $statusable;
	var $status_active = true; // so if user no status priv all new record will be inactive
	                            // false = inactive, true = active;
	
	var $inactive_style = 'color: #5F5F5F;';
	 
	var $append_str = '';							
	var $controller;
	var $msg = array();
	var $use_detail = false;
										 
	
	function AppView() {
		
		$reg =& Registry::instance();
		$this->controller =& $reg->getEntry('controller');
		$this->conf =& $reg->getEntry('conf');
		$this->priv =& $reg->getEntry('priv');
		$this->extra =& $reg->getEntry('extra');
		
		$this->template_dir = $this->controller->working_dir.'template/';
		$this->setCommonMsg();
		$this->setModuleMsg();
		$this->setPopup(@$_GET[$this->popup_var]);
		
		$this->encoding = $this->conf['lang']['meta_charset'];
	}
	
	
	function getLink($module = false, $page = false, $sub_page = false, $action = false, $more = array()) {
		return $this->controller->getLink($module, $page, $sub_page, $action, $more);
	}	
	
	// set common msg
	function setCommonMsg() {
		$file = AppMsg::getCommonMsgFile('common_msg.ini');
		$this->msg = array_merge($this->msg, AppMsg::parseMsgs($file, false, false));		
	}
	
	// set concrete module msg
	function setModuleMsg($module = false) {
		$module = (!$module) ? $this->controller->module : $module;
		$file = AppMsg::getModuleMsgFile($module, 'common_msg.ini');
		
		$this->msg = array_merge($this->msg, AppMsg::parseMsgs($file));
	}
	
	// this for shorten in sorting
	function setShortMsg($msg, $num = 5) {
		$str = '<span title="%s">%s.</span>';
		$this->msg[$msg] = sprintf($str, $this->msg[$msg],  substr($this->msg[$msg], 0, $num));
	}
	
	
	// when we need to add additonal lang file
	function addMsg($file_name, $module = false) {
		
		if($module) {
			$file_name = AppMsg::getModuleMsgFile($module, $file_name);
		} else {
			$file_name = AppMsg::getCommonMsgFile($file_name);
		}		
		
		$this->msg = array_merge($this->msg, AppMsg::parseMsgs($file_name));
	}
	
	
	// setting pop_up, if window popup or not to display 
	// appropriate template for some lists
	function setPopup($val = false) { 
		$this->popup = $val;
	}
	

	
	// create buttons, add new, ...
	function getButton($link, $msg, $new_window = false) {
		
		$link = (!$new_window) ? sprintf('<a href="%s" class="btnLink">%s</a>', $link, $msg) 
		                       : sprintf("<a href=\"javascript:OpenWin('%s', '123123123', '730', '550', 'yes', false,1)\" class=\"btnLink\">%s</a>",  $link, $msg);
			
		$html =	
		'<table cellpadding=0 cellspacing=0><tr>
		<td><img src="images/button/btn_left.gif" width="20" height="20"></td>
		<td background="images/button/btn_bgr.gif" nowrap style="padding: 0px 10px;">'.$link.'</td>
		<td><img src="images/button/btn_right.gif" width="2" height="20"></td>
		</tr></table>' . "\n";
			
		return $html;
	}
	
	
	function getChecked($var) {
		return ($var) ? 'checked' : '';
	}
	
	
	function getFormatedDate($timestamp, $format = null) {
		$format = ($format) ? $format : $this->conf['lang']['date_format'];
		return $this->_getFormatedDate($timestamp, $format);
	}
	
	
	// generate link for update, delete, etc.
	function getImgLink($path, $img, $msg, $confirm_msg = false) {
		
		$confirm = ($confirm_msg) ? sprintf("onClick=\"return window.confirm('%s')\"", $confirm_msg) : '';
		$img_tag = sprintf('<img src="images/icons/%s.gif" alt="%s" border="0">', $img, $msg);
		$link = ($path) ? sprintf('<a href="%s" title="%s" %s>%s</a>', $path, $msg, $confirm, $img_tag) 
						: $img_tag;
		return $link;
	}	
	
	
/*
	function _getActionLink($common_link, $action_key, $action_value, $id_key, $record_id, $more_params = array()) {
		
		$str = '%s&%s=%s&%s=%d';
		$str = sprintf($str, $common_link, $action_key, $action_value, $id_key, $record_id);
		
		if($more_params) {
			
		}
		
		return $str;
	}
	
	// $more_params - array(key=value, key=value);
	function getActionLink($action_val, $record_id, $more_params = array()) {
		
		//_getActionLink($common_link, $action_key, $action_value, $id_key, $record_id, $more_params = array()) {
		$action_val1 = $this->controller->getActionValue($action_val);
		$action_val = ($action_val1) ? $action_val1 : $action_val;
		
		if($more_params) {
			$more_params = implode('&', $more_params);
		}
		
		return $this->_getActionLink($this->controller->getCommonLink(),
		                             $this->controller->getRequestKey('action'),
									 $action_val,
									 $this->controller->id_key,
									 $record_id,
									 $more_params);
	}
*/
	
	
	function _getActionLink($action_value, $record_id = false, $more_params = array()) {
		
		$common_link = $this->controller->getCommonLink();
		$action_key = $this->controller->getRequestKey('action');
		
		$id_param = ($record_id) ? sprintf("&%s=%d", $this->controller->id_key, $record_id) : '';
		
		$action_val = $this->controller->getActionValue($action_value);
		$action_value = ($action_val) ? $action_val : $action_value;
		
		$more_params = ($more_params) ? '&' . http_build_query($more_params) : '';
		
		$str = '%s&%s=%s%s%s';
		$str = sprintf($str, $common_link, $action_key, $action_value, $id_param, $more_params);
		
		return $str;
	}
	
	// $more_params - array(key=value, key=value);
	function getActionLink($action_val, $record_id = false, $more_params = array()) {
		return $this->_getActionLink($action_val, $record_id, $more_params);
	}
	
	
	// used it to set links such as delete, update
	function getViewListVars($record_id = false, $active = NULL) {
		static $i = 0;
		
		$row['common_link'] = $this->controller->getCommonLink();
		$common_link = $row['common_link'];
		$action_key = $this->controller->getRequestKey('action');

		//$row['print_link'] = $row['common_link'] . '&' . $this->popup_var . '=1';

		$row['class'] = ($i++ & 1) ? 'trDarker' : 'trLighter'; // rows colors
		$row['style'] = ($active !== null && !$active) ? $this->inactive_style : ''; // style for not active
		
		$row['add_link'] = sprintf('%s&%s=%s', $row['common_link'], $action_key, $this->controller->getActionValue('insert'));
		
		// active link
		if(!$this->priv->isPriv('status')) {
			$active = ($active == 0) ? 'not' : 'not_checked';
		}
		
		if($active == 'not') {
			$row['active_img'] = $this->getImgLink('', 'active_d_0', '');
		
		} elseif($active == 'not_checked') {
			$row['active_img'] = $this->getImgLink('', 'active_d_1', '');
		
		} else {
			$active_var = ($active == 0) ? '1' : '0';
			$active_img = ($active == 0) ? 'active_0' : 'active_1';
			$row['active_link'] = $this->getActionLink('status', $record_id) . '&status=' . $active_var;
			$row['active_img'] = $this->getImgLink($row['active_link'], $active_img, $this->msg['set_status_msg'], $this->msg['sure_status_msg']);
		}
		
		
		// detail
		$row['detail_link'] = $this->getActionLink('detail', $record_id);
		$row['detail_img'] = $this->getImgLink($row['detail_link'], 'load', $this->msg['detail_msg']);
		

		// update
		if($this->priv->isPriv('update')) {
			$row['update_link'] = $this->getActionLink('update', $record_id);
			$row['update_img'] = $this->getImgLink($row['update_link'], 'update', $this->msg['update_msg']);		
		} elseif($this->use_detail) {
			$row['update_link'] = $this->getActionLink($action_val, $record_id);	
			$row['update_img'] = $this->getImgLink($row['update_link'], 'update', $this->msg['detail_msg']);					
		} else {
			$row['update_link'] = $this->controller->getCurrentLink();
		}
		
		
		// delete
		if($this->priv->isPriv('delete')) {		
			$row['delete_link'] = $this->getActionLink('delete', $record_id);
			$row['delete_img']	= $this->getImgLink($row['delete_link'], 'delete', $this->msg['delete_msg'], $this->msg['sure_delete_msg']);
		}
		
		return $row;
	}	
	
	
	// this is for form
	function setCommonFormVars(&$obj, $add_msg = false, $update_msg = false) {
		
		$add_msg = ($add_msg !== false) ? $add_msg : $this->msg['add_new_msg'];
		$update_msg = ($update_msg !== false) ? $update_msg : $this->msg['update_msg'];
		
		$row['action_title'] = ($this->controller->getAction() == 'insert') ? $add_msg : $update_msg;
		$row['action_link'] = $this->controller->getCurrentLink();
		
		$row['cancel_link'] = $this->controller->getCommonLink();
		$row['full_cancel_link'] = ($this->popup) ? 'window.close()'
												  : sprintf("location.href='%s'", $this->controller->getCommonLink());
		
		$row['required_sign'] = '<span class="requiredSign">*</span>';
		
		// hidden fields in form to remember a state
		$arr = array();
		foreach($obj->hidden as $v) {
			$arr[$v] =& $obj->properties[$v];
		}
		
		$row['hidden_fields'] = http_build_hidden($arr);
		
		return $row;
	}
	
	
	// this is for form
	function setCommonFormVarsFilter() {
		$row['hidden_fields'] = http_build_hidden($this->controller->full_page_params);
		return $row;
	}	
	
	
	// to set field active in form depends on user priv
	function setStatusFormVars($active, $use_priv = true) {
		
		$action_key = $this->controller->getRequestVar('action');
		
		if($action_key == 'insert') {
			$is_statusable = ($this->priv) ? $this->priv->isPriv('status') : true;
			$active = ($is_statusable);
		} else {
			$is_statusable = ($this->priv) ? $this->priv->checkPrivAction('status') : true;
		}
		
		
		$str = '';
		$data = array();
		if(!$is_statusable || !$active) {
			$str = '<input type="hidden" name="active" value="%s">';
			$str = sprintf($str, $active);
		} elseif($active) {
			$str = '<input type="hidden" name="active" value="%s">';
			$str = sprintf($str, 0);
		}
		
		$disabled = ($is_statusable) ? '' : 'disabled';
		$checked = ($active) ? 'checked' : '';
		
		$checkbox = '<input type="checkbox" name="active" value="%s" %s %s> %s';
		$str .= sprintf($checkbox, 1, $disabled, $checked, $this->msg['yes_msg']); 
		$data['status_checkbox'] = $str;
		
		return $data;
	}
	
	
	// return string with hidden fields
	// $arr = array with vars to generate hidden
	// $arr_to_skip = what keys to skip
	function getHiddenFields($arr, $arr_to_skip = array()) {
		foreach($arr as $k => $v) {
			if(in_array($k, $arr_to_skip))  { continue; }
 			$arr1[$k] = $arr[$k];
		}
		return http_build_hidden($arr1);
	}
	
	
	function &pageByPage($limit, $sql, $per_page = true, $user_form = true, $limit_range = array()) {
		
		require_once 'eleontev/PageByPage.php';
	
		$bp = new PageByPage($limit, $_GET);
		$bp->setMsg($this->msg['page_msg'], $this->msg['record_msg'], $this->msg['record_from_msg']);
		$bp->setPerPageMsg($this->msg['per_page_msg']);
		$bp->use_form = $user_form;
		$bp->per_page_range = ($limit_range) ? $limit_range : $this->conf['limit_range'];
		
		$bp->countAll($sql);
		$bp->nav =& $bp->navigate($per_page); 
		
		return $bp;
	}
	
	
	// generate page by page navigation, some buttons, ...
	//function & commonHeaderList($nav, $button_msg = true) {
	function &commonHeaderList($nav = '', $left_side = '', $button_msg = true) {	
		
		$msg_box = '';
		
		// common tips on page
		if($this->controller->sub_page)  { $keyword =  $this->controller->sub_page; }
		elseif ($this->controller->page) { $keyword =  $this->controller->page; }
		else                             { $keyword =  $this->controller->module; }
		
		//$msg_box = &AppMsg::hintBox($keyword, $this->controller->module);
		
		// after wrong action
		$msg_key = $this->controller->getRequestVar('show_msg');
		if($msg_key) {
			$msg_box = &AppMsg::afterActionBox($msg_key, 'error');
		}
		
		
		$links =& $this->getViewListVars();
		$tpl = new tplTemplatez(APP_TMPL_DIR . 'common_list_header.html');
		
		
		if(is_array($button_msg)) {
			$buttons = array();
			$buttons[] = '<table><tr>';
			foreach($button_msg as $msg => $link) {
				if($link == 'insert' && $this->priv->isPriv('insert')) {
					$button_msg = (!$msg) ? $this->msg['add_new_msg'] : $msg;
					$buttons[] = sprintf('<td>%s</td>', $this->getButton($links['add_link'], $button_msg));				
				} else {
					$buttons[] = sprintf('<td>%s</td>', $this->getButton($link, $msg));
				}
			}
			
			$buttons[] = '</tr></table>';
			$tpl->tplAssign('add_link', implode('', $buttons));
		
		} elseif($button_msg !== false && $this->priv->isPriv('insert')) {
			$button_msg = ($button_msg === true) ? $this->msg['add_new_msg'] : $button_msg;
			$tpl->tplAssign('add_link', $this->getButton($links['add_link'], $button_msg));
		}
		
		if($nav) {
			$tpl->tplSetNeeded('/by_page');
			$tpl->tplAssign('by_page_tpl', $nav);
		}
		
		if($left_side) {
			$tpl->tplAssign('left_side', $left_side);
		}
		
		$tpl->tplParse();
		$t = $msg_box . $tpl->tplPrint(1);
		return  $t;
	}
}
?>